package com.zhu.tool_test.starke.util.lang;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZTrue
 * @version V1.0
 * @description 浮点型工具类
 * @date Create at 2019/3/11
 */
public class Doubles {
    public static boolean isNullOrEmpty(Double... values) {
        for (Double v : values) {
            if (v == null || v == 0) {
                return true;
            }
        }
        return false;
    }

    public static boolean isNotNullOrEmpty(Double... values) {
        return !isNullOrEmpty(values);
    }

    /**
     * 保留n位小数
     *
     * @param target 目标浮点数
     * @param count  保留位数
     * @return 结果
     */
    public static Double toFixed(Double target, int count) {
        if (count == -1) {
            return target;
        }
        StringBuilder builder = new StringBuilder("##0.");
        for (int i = 0; i < count; i++) {
            builder.append("0");
        }
        DecimalFormat format = new DecimalFormat(builder.toString());
        String tmp = format.format(target);
        return Double.valueOf(tmp);
    }

    public static String toStringFixed(Double target, int count) {
        if (count < 0) {
            throw new IllegalArgumentException(
                    "The   scale   must   be   a   positive   integer   or   zero");
        }
        if (count == 0) {
            return new DecimalFormat("0").format(target);
        }
        String formatStr = "0.";
        for (int i = 0; i < count; i++) {
            formatStr = formatStr + "0";
        }
        return new DecimalFormat(formatStr).format(target);
    }

    /**
     * 将一个数组进行保留n位小数操作
     *
     * @param count  保留位数
     * @param values 目标浮点数组
     * @return 浮点结果
     */
    public static Double[] toFixed(int count, Double... values) {
        List<Double> list = new ArrayList<>();
        for (Double f : values) {
            list.add(toFixed(f, count));
        }
        Double[] fs = new Double[list.size()];
        return list.toArray(fs);
    }

    /**
     * 将一个字符串数组(内容为小数)进行保留n位小数操作
     *
     * @param count  保留位数
     * @param values 目标字符串数组
     * @return 浮点结果
     */
    public static Double[] toFixed(int count, String... values) {
        Double[] fs = new Double[values.length];
        for (int i = 0; i < values.length; i++) {
            if (null == values[i]) {
                fs[i] = -1.0;
                continue;
            }
            fs[i] = Double.valueOf(values[i]);
        }
        return toFixed(count, fs);
    }
}
